<template>
  <div class="list">
    <a-button type="primary" class="base-mb10" @click="openModal">+ {{ $t('self.user.tips1') }}</a-button>

    <!-- :label-col="{span: 5}"-->
    <a-form
        ref="searchFormRef"
        class="search-form base-mb15"
        :model="searchFormState"
        @finish="onSearchFinish"
    >
      <a-row :gutter="[10, 24]">
        <a-col :span="5">
          <a-form-item name="mobile" :label="$t('self.user.tips2')">
            <a-input v-model:value="searchFormState.mobile"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="5">
          <a-form-item name="userName" :label="$t('self.user.tips3')">
            <a-input v-model:value="searchFormState.userName"></a-input>
          </a-form-item>
        </a-col>
<!--        <a-col :span="6">-->
<!--          <a-form-item name="orgId" :label="$t('self.user.tips4')">-->
<!--            <a-select v-model:value="searchFormState.orgId" :options="searchOrgOptions" :fieldNames="{label: 'orgName',value: 'id'}" :placeholder="$t('self.pleaseChoose')"/>-->
<!--          </a-form-item>-->
<!--        </a-col>-->
        <a-col :span="5">
          <a-form-item name="status" :label="$t('self.user.tips5')">
            <a-select v-model:value="searchFormState.status" :options="[{ label: $t('self.user.tips6'), value: 1 },{ label: $t('self.user.tips71'), value: 0 }]" :placeholder="$t('self.pleaseChoose')" allow-clear @change="onChangeStatus"  />
          </a-form-item>
        </a-col>
        <a-col :span="3" class="base-flex base-rows">
          <a-button type="primary" html-type="submit">{{ $t('self.searchButton') }}</a-button>
          <a-button class="base-ml10" @click="resetSearchForm">{{ $t('self.resetButton') }}</a-button>
        </a-col>
      </a-row>
    </a-form>

    <s-table ref="stableRef" :api-obj="tableConfig.apiObj" api-method="POST" 
    :scroll="{ x: 2400 }"
    :params="tableConfig.apiParams" :columns="sourceColumn" row-key="id"  
    :light-index="tableConfig.lightIndex" :is-row-selection="false" 
    @selectionChange="tableSelectionChange" :is-show-tool="false">

      <template #bodyCell="{ column, record, index }">

        <!--帐户状态-->
        <template v-if="column.key === 'status'">
          <!-- Status: (1、Active, 0、Inactive, 2、Blocked, 3、Deleted) -->
          <template v-if="!record[column.key]">
            <sc-status-indicator type="warning"></sc-status-indicator>
            Inactive
          </template>
          <template v-if="record[column.key] === 1">
            <sc-status-indicator type="success"></sc-status-indicator>
            Active
          </template>
          <template v-if="record[column.key] === 2">
            <sc-status-indicator type="primary"></sc-status-indicator>
            Blocked
          </template>
          <template v-if="record[column.key] === 3">
            <sc-status-indicator type="danger"></sc-status-indicator>
            Deleted
          </template>
        </template>


        <!--获取运营商名称-->
        <template v-if="column.key === 'orgId'">
          {{ getOrgNameByOrgId(record[column.key]) }}
        </template>

        <template v-if="column.key === 'action'">
            <span>
              <!--1（ Active 正常）,  2( Blocked 冻结)  -->
              <a-popconfirm
                  :title="$t('self.user.tips22')"
                  :ok-text="$t('self.yesTxt')"
                  :cancel-text="$t('self.noTxt')"
                  @confirm="handleActive(record, index)"
                  v-if="record.status === 2"
              >
                <a href="javascript:void(0)">{{ $t('self.user.tips72') }}</a>
              </a-popconfirm>

              <a-popconfirm
                  :title="$t('self.user.tips21')"
                  :ok-text="$t('self.yesTxt')"
                  :cancel-text="$t('self.noTxt')"
                  @confirm="handleRrozen(record, index)"
                  v-if="record.status === 1"
              >
                <a href="javascript:void(0)">{{ $t('self.user.tips71') }}</a>
              </a-popconfirm>

              <a-divider type="vertical"/>
              <a-popconfirm
                  :title="$t('self.confirmDelete')"
                  :ok-text="$t('self.yesTxt')"
                  :cancel-text="$t('self.noTxt')"
                  @confirm="handleDelete(record, index)"
              >
                <a href="javascript:void(0)">{{ $t('self.delete') }}</a>
              </a-popconfirm>

<!--              <a href="javascript:void(0)" @click="openRecordModal(record, index)">{{ $t('self.user.tips14') }}</a>-->
<!--              <a-divider type="vertical"/>-->
<!--              <a href="javascript:void(0)" @click="openRechargeModal(record, index)">{{ $t('self.user.tips12') }}</a>-->
            </span>
        </template>

      </template>
    </s-table>

    <editModal ref="modalRef" @ok="stableRef.refresh()" @close=""></editModal>
    <recordModal ref="recordModalRef"></recordModal>
    <rechargeModal ref="rechargeModalRef"></rechargeModal>
  </div>
</template>

<script setup>
import { getCurrentInstance, nextTick, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import ScStatusIndicator from '@/components/scMini/scStatusIndicator.vue'
import { mainStore } from '@/stores/mainStore'
import editModal from './edit_modal.vue'
import recordModal from './record_modal.vue'
import rechargeModal from './recharge_modal.vue'
import { message } from 'ant-design-vue'
const { proxy } = getCurrentInstance()
const $TOOL = proxy.$TOOL
const $API = proxy.$API
const $T = proxy.$t
const route = useRoute()
const router = useRouter()
const useMainStore = mainStore()

const selectedKey = ref([])
const stableRef = ref(null)
const tableConfig = ref({
  apiObj: $API.backend.user.list,
  apiParams: {
    status: 1
  },
  lightIndex: [] // 要高亮的行号
})
// 表格列
const sourceColumn = ref([])

onMounted(async () => {

  // 获取表格列
  resetDefaultOptionsByLang()
  // 获取运营商下拉数据
  searchOrgOptions.value = await proxy.getOrgSelectList(true)

})

// 监听 lang 状态
watch(
    () => useMainStore.lang, // 切换语言包时
    (curr, old) => {
      // console.log('语言包', curr)
      // 获取表格列
      resetDefaultOptionsByLang()
    }
);

const resetDefaultOptionsByLang = () => {
  sourceColumn.value = [
    {
      title: 'S/N',
      dataIndex: 'serial',
      key: 'serial',
    },
    {
      title: 'Operator',
      dataIndex: 'orgName',
      key: 'orgName'
    },
    {
      title: 'Customer Name',
      dataIndex: 'userName',
      key: 'userName'
    },
    {
      title: 'Email',
      dataIndex: 'email',
      key: 'email'
    },
    {
      title: 'Phone Number',
      dataIndex: 'mobile',
      key: 'mobile'
    },
    {
      title: 'City | country',
      dataIndex: 'city',
      key: 'city',
      customRender: ({record}) => {
			  return (record.city + '-' + record.country);
		  },
    },
    {
      title: 'Wallet Balance',
      dataIndex: 'totalMoney',
      key: 'totalMoney'
    },
    {
      title: 'Vehicle Type',
      dataIndex: 'vehicleType',
      key: 'vehicleType'
    },



    {
      title: 'Vehicle Chassis',
      dataIndex: 'VehicleChassis',
      key: 'VehicleChassis'
    },
    {
      title: 'Plate Number',
      dataIndex: 'plateNumber',
      key: 'plateNumber'
    },
    {
      title: 'Color',
      dataIndex: 'color',
      key: 'color'
    },
    {
      title: 'Brand Model',
      dataIndex: 'brandModel',
      key: 'brandModel'
    },
    {
      title: 'Keyfob Type',
      dataIndex: 'KeyfobType',
      key: 'KeyfobType'
    },
    {
      title: 'Keyfob Color',
      dataIndex: 'keyfobColor',
      key: 'keyfobColor'
    },
    {
      title: 'Assign Uuid',
      dataIndex: 'assignUuid',
      key: 'assignUuid'
    },
    {
      title: 'Assign Keyfob',
      dataIndex: 'assignKeyfob',
      key: 'assignKeyfob'
    },
    // {
    //   title: 'User No',
    //   dataIndex: 'userNo',
    //   key: 'userNo'
    // },
    {
      title: 'User Status',
      dataIndex: 'status',
      key: 'status',
      // 可选：添加状态文本映射（如果后端返回的是数字）
      customRender: ({ text }) => {
        const statusMap = {
          1: 'Active',
          0: 'Inactive',
          2: 'Blocked',
          3: 'Deleted'
        }
        return statusMap[text] || text
      }
    },
    {
      title: 'Created on',
      dataIndex: 'createOn',
      key: 'createOn'
    },
    {
      title: 'Create Time',
      dataIndex: 'createTime',
      key: 'createTime'
    },
    // {
    //   title: $T('self.user.tips4'),
    //   dataIndex: 'orgId',
    //   key: 'orgId',
    //   // // 自定义显示列内容
    //   // customRender: ({text, record}) => {
    //   //   // 接口返回是秒，处理为分
    //   //   console.log(text)
    //   //   return proxy.getOrgNameByOrgId(text)
    //   // },
    // },
    { title: $T('self.actionButton'), key: 'action', ellipsis: true, fixed: 'right', width: 150 }
  ]
}

const tableSelectionChange = (rows, record) => {
  selectedKey.value = rows
  // console.log('表格选择项', rows, record)
}

// =========start search表单
const searchFormRef = ref(null)
const searchFormState = ref({
  mobile: '',     // 手机号码
  userName: '',   // 用户帐号
  orgId: null,    // 运营商户
  status: 1,   // 帐户状态，默认是正常状态
})
const searchOrgOptions = ref([])

const onChangeStatus = (val) => {
  if(val === undefined) {
    tableConfig.value.apiParams = null
  }
  console.log('表格传参', tableConfig.value.apiParams)
  console.log('状态值', val)
}
const onSearchFinish = (values) => {
  const params = $TOOL.array.cleanParams(values)
  // console.log(params)
  // stableRef.value.upData(params, 1)
  stableRef.value.reload(params, 1)
}
// 重置搜索表单
const resetSearchForm = () => {
  searchFormRef.value.resetFields()
}
// =========end search表单

const modalRef = ref(null)
const openModal = (record, index) => {
  if (index !== undefined) {
    // 编辑
    tableConfig.value.lightIndex = [index] // 仅高亮当前行
    nextTick(() => {
      modalRef.value.edit(record)
    })
  } else {
    // 新增
    modalRef.value.add()
  }
}

const recordModalRef = ref(null)
const openRecordModal = (record, index) => {
  tableConfig.value.lightIndex = [index] // 仅高亮当前行
  nextTick(() => {
    recordModalRef.value.show(record.id)
  })
}

const rechargeModalRef = ref(null)
const openRechargeModal = (record, index) => {
  tableConfig.value.lightIndex = [index] // 仅高亮当前行
  nextTick(() => {
    rechargeModalRef.value.show(record)
  })
}

// 启用当前用户
const handleActive = (record) => {
  // 1（ Active 正常）,  2( Blocked 冻结)
  $API.backend.user.updateUserStatus.post({
    userId: record.userId,
    status: 1
  }).then(() => {
    message.success($T('self.message.success'))
    stableRef.value.refresh()
  }).catch(err => {
    message.error(err.msg || $T('self.message.error'))
  })
}

// 禁用/冻结当前用户
const handleRrozen = (record) => {
  // 1（ Active 正常）,  2( Blocked 冻结)
  $API.backend.user.updateUserStatus.post({
    userId: record.userId,
    status: 2
  }).then(() => {
    message.success($T('self.message.success'))
    stableRef.value.refresh()
  }).catch(err => {
    message.error(err.msg || $T('self.message.error'))
  })

}

// 删除用户
const handleDelete = (record) => {
  $API.backend.user.delete.post({
    userId: record.userId,
  }).then(() => {
    message.success($T('self.message.success'))
    stableRef.value.refresh()
  }).catch(err => {
    message.error(err.msg || $T('self.message.error'))
  })
}
</script>

<style lang="scss" scoped>
.list {
  height: 100%;
  background: #ffffff;
  padding: 15px;

  .search-form {
    padding: 16px;
    background: rgb(247, 248, 250);

    :deep(.ant-form-item) {
      margin-bottom: 0;
    }
  }
}
</style>
